import {Message} from 'view-design'

export function blobToBase64(blob) {
    return new Promise((resolve, reject) => {
        const fileReader = new FileReader();
        fileReader.readAsDataURL(blob)
        fileReader.onload = (result) => {
            resolve('data:' + blob.type + ';' + result.target.result)
        }
        fileReader.onerror = (error) => {
            reject(error)
        }
    })
}

export function blobToString(blob) {
    return new Promise((resolve, reject) => {
        const fileReader = new FileReader();
        fileReader.readAsText(blob)
        fileReader.onload = (result) => {
            resolve(result.target.result)
        }
        fileReader.onerror = (error) => {
            reject(error)
        }
    })
}


export function base64ToImageData(base64) {
    return new Promise((resolve, reject) => {
        const img = new Image();
        img.onload = () => {
            const canvas = document.createElement("canvas");
            const context = canvas.getContext("2d");
            canvas.width = img.width;
            canvas.height = img.height;
            if (!context) {
                reject(new Error("context is null"));
                return;
            }
            context.drawImage(img, 0, 0);
            const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
            resolve(imageData);
        };
        img.onerror = (error) => {
            reject(error);
        };

        img.src = base64;

    });
}

export function throttle(fn, duration = 2000) {
    let timer = null;
    let lastTime = Date.now();
    return function (...rest) {
        let now = Date.now();
        if (now - lastTime >= duration) {
            clearTimeout(timer);
            timer = null;
            lastTime = now;
            return fn.apply(this, rest);
        } else if (!timer) {
            timer = setTimeout(() => {
                return fn.apply(this, rest);
            }, duration)
        }
    }
}

/**
 * 防抖
 */
export function debounce(fn, delay = 2000) {
    let timer = null;
    return function (...rest) {
        if (!timer) {
            fn.apply(this, rest);
        }
        clearTimeout(timer);
        timer = setTimeout(() => {
            fn.apply(this, rest);
        }, delay)
    }
}

export function fileImport(callback, {filesType = '*'}) {
    const currentInput = document.getElementById('fileImport')
    if (currentInput) {
        document.body.removeChild(currentInput)
    }
    const input = document.createElement('input')
    input.id = 'fileImport'
    input.type = 'file'
    input.accept = filesType
    input.style.display = 'none'
    document.body.appendChild(input)
    input.onchange = (e) => {
        if (filesType === '*') {
            callback(e)
            return;
        }
        const file = e.target.files[0]
        const fileSuffixArr = file.name.split('.');
        const fileSuffix = fileSuffixArr[fileSuffixArr.length - 1]
        // const fileType = file.type
        if (filesType.includes(fileSuffix)) {
            callback(e)
        } else {
            Message.error('请选择' + filesType + '类型的文件')
        }
    }

    input.click()

}

// 文件导出
export function fileExport(_content, _filename, type) {
    if (!_content) return;
    const blob = new Blob([_content], type)
    const fileName = _filename;
    if ('download' in document.createElement('a')) { // 非IE下载
        const elink = document.createElement('a')
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)
    } else { // IE10+下载
        navigator.msSaveBlob(blob, fileName)
    }
}
